#include <my_head.h>

int main(int argc, const char *argv[]){
    if(3 != argc){
        printf("Usage : %s <file_server> <file_client>\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    // 创建套接字
    int sockfd = socket(PF_UNIX, SOCK_DGRAM, 0);
    if(-1 == sockfd)
        ERR_LOG("socket error");
    
    // 填充服务器本地结构体
    struct sockaddr_un serveraddr;
    serveraddr.sun_family = AF_UNIX;
    strcpy(serveraddr.sun_path, argv[1]);
    socklen_t serveraddr_len = sizeof(serveraddr);

    // 客户端绑定自己的本地结构体
    struct sockaddr_un clientaddr;
    clientaddr.sun_family = AF_UNIX;
    strcpy(clientaddr.sun_path, argv[2]);
    socklen_t clientaddr_len = sizeof(clientaddr);
    if(-1 == bind(sockfd, (struct sockaddr *)&clientaddr, clientaddr_len))
        ERR_LOG("bind error");

    // 收发数据
    char buff[128] = {0};
    while(1){
        fgets(buff, sizeof(buff), stdin);
        buff[strlen(buff)-1] = '\0';
        // 给服务器发送数据
        if(-1 == sendto(sockfd, buff, sizeof(buff), 0, (struct sockaddr *)&serveraddr, serveraddr_len)){
            ERR_LOG("sendto error");
        }
        // 接收服务器回复的消息
        memset(buff, 0, sizeof(buff)); // 清空buff
        // 这里就无需再保存服务器的网络信息结构体了 因为我们serveraddr 填充后没被修改过
        if(-1 == recvfrom(sockfd, buff, sizeof(buff), 0, NULL, NULL)){
            ERR_LOG("recvfrom error");
        }
        // 将收到的消息打印到终端
        printf("服务器回复:[%s]\n", buff);
    }
    // 关闭套接字
    close(sockfd);

    return 0;
}